import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
axios.defaults.baseURL = localStorage.getItem('api_url') || 'https://api-xwjd-mgr.xingchenga.xyz'
axios.interceptors.request.use(function (config) {
    //过滤第三方chatGPT_api不添加登入用户的token
    if (config.headers['X-DashScope-Async'] != 'enable' && config.headers['type'] != 'send') {
        localStorage.token && (config.headers.Authorization = localStorage.token)
    }
    return config
})
// 添加响应拦截器
axios.interceptors.response.use(
    (response) => {
        if (response.config.url.indexOf('dashscope.aliyuncs.com') !== -1||response.config.url.indexOf('https://www.electronjs.org') !== -1) {
            return Promise.resolve(response)
        }
        switch (response.data.code) {
            case 200:
                return Promise.resolve(response.data.data)
            case 401:
            case 403:
                ElMessage.error(response.data.message || response.data.error)
                router.push('/login')
                break
            default:
                ElMessage.error(response.data.message || response.data.error)
                return Promise.reject(response)
        }
    },
    (error) => {
        if (error.response) {
            switch (error.response.status) {
                case 404:
                    ElMessage.error(error.response.data.message)
                    break
                case 500:
                    ElMessage.error('服务器出现故障,请联系管理员')
                    break
                case 502:
                    ElMessage.error('服务器正在维护,请稍后重试')
                    router.push('/login')
                    break
            }
        }
        return Promise.reject(error)
    }
)
export default axios
